//
//  MainMenuScene.m
//  GameProject
//
//  Created by Blair Trusler on 21/07/2011.
//  Copyright 2011 Blair Trusler. All rights reserved.
//

#import "GameHeader.h"
#import <GameKit/GameKit.h>
#import <UIKit/UIKit.h>

@implementation MainMenuScene

+(id) scene
{
    CCScene *scene = [CCScene node];
    
    MainMenuScene *layer = [MainMenuScene node];
    
    [scene addChild: layer];
    
    return scene;
}

#pragma mark - platform
- (NSString *) platform{
    size_t size;
    sysctlbyname("hw.machine", NULL, &size, NULL, 0);
    char *machine = malloc(size);
    sysctlbyname("hw.machine", machine, &size, NULL, 0);
    NSString *platform = [NSString stringWithUTF8String:machine];
    free(machine);
    return platform;
}

- (NSString *) platformString{
    NSString *platform = [self platform];
    if ([platform isEqualToString:@"iPhone1,1"])    return @"iPhone 1G";
    if ([platform isEqualToString:@"iPhone1,2"])    return @"iPhone 3G";
    if ([platform isEqualToString:@"iPhone2,1"])    return @"iPhone 3GS";
    if ([platform isEqualToString:@"iPhone3,1"])    return @"iPhone 4";
    if ([platform isEqualToString:@"iPhone4,1"])    return @"iPhone 4S";
    if ([platform isEqualToString:@"iPhone3,3"])    return @"Verizon iPhone 4";
    if ([platform isEqualToString:@"iPod1,1"])      return @"iPod Touch 1G";
    if ([platform isEqualToString:@"iPod2,1"])      return @"iPod Touch 2G";
    if ([platform isEqualToString:@"iPod3,1"])      return @"iPod Touch 3G";
    if ([platform isEqualToString:@"iPod4,1"])      return @"iPod Touch 4G";
    if ([platform isEqualToString:@"iPad1,1"])      return @"iPad";
    if ([platform isEqualToString:@"iPad2,1"])      return @"iPad 2 (WiFi)";
    if ([platform isEqualToString:@"iPad2,2"])      return @"iPad 2 (GSM)";
    if ([platform isEqualToString:@"iPad2,3"])      return @"iPad 2 (CDMA)";
    if ([platform isEqualToString:@"i386"])         return @"Simulator";
    if ([platform isEqualToString:@"x86_64"])       return @"Simulator";
    return platform;
}


-(id) init {
    
    if( (self=[super init] )) {
        CCLOG(@"Loading Main Menu...");
        
        platformType = [self platformString];
        CCLOG(@"RUNNING ON: %@",platformType);
        
        levelPlayed = 0;    //Prev level played = 0 (configs Options Menu accordingly)
        
        [AudioManager playMainMenuMusic];
       // [[SimpleAudioEngine sharedEngine] playBackgroundMusic:@"level3Music.wav"]; //http://www.freesound.org/people/Xythe/sounds/81392/ 
        
        tempVC=[[UIViewController alloc] init]; //Init temp VC for Game Center button

        [self setUpMenu];
        [self rewardAchievements];
        
        CCLOG(@"Main Menu Loaded.");
    }
    return self;
}

-(void)rewardAchievements{
    //Award achievement 
    if (![GameState sharedInstance].achievement10){
        [GameState sharedInstance].achievement10 = TRUE;
        [[GameState sharedInstance]save];
        [[GameCenterLogin sharedInstance] reportAchievement:kAchievement10 percentComplete:100.0];
//        NSString *achievementName = [NSString stringWithFormat:kAchievement10];
//        CCLOG(@"Awarded Achievement - %@",achievementName);
    }
}

-(void)setUpMenu{
    CCSprite *backgroundImage = [CCSprite spriteWithFile:@"GameBackground.png"];
    CCSprite *textImage = [CCSprite spriteWithFile:@"GameTitleText.png"];
    
    [backgroundImage runAction:[CCRepeatForever actionWithAction:[CCSequence actions:[CCFadeIn actionWithDuration:4.0f],[CCFadeOut actionWithDuration:8.0f],nil]]];
    
    CGSize screenSize = [[CCDirector sharedDirector] winSize]; 
    [backgroundImage setPosition:CGPointMake(screenSize.width/2, screenSize.height/2)]; 
            
    CCMenuItemImage *playGameButton = [CCMenuItemImage itemFromNormalImage:@"LevelSelect.png" selectedImage:@"LevelSelect1.png" target:self selector:@selector(levelSelect:)];
    CCMenu *playGameMenu = [CCMenu menuWithItems:playGameButton, nil];
    
    CCMenuItemImage *creditsButton = [CCMenuItemImage itemFromNormalImage:@"Credits.png" selectedImage:@"Credits1.png" target:self selector:@selector(loadCreditsScene:)];
    CCMenu *creditsMenu = [CCMenu menuWithItems:creditsButton, nil];
    CCMenuItemImage *guideButton = [CCMenuItemImage itemFromNormalImage:@"Guide.png" selectedImage:@"Guide1.png" target:self selector:@selector(loadGuideScene:)];
    CCMenu *guideMenu = [CCMenu menuWithItems:guideButton, nil];
    
    CCMenuItemImage *achievementsButton = [CCMenuItemImage itemFromNormalImage:@"GameCenterIcon.png" selectedImage:@"GameCenterIcon.png" target:self selector:@selector(showAchievements:)];
    CCMenu *achieveMenu = [CCMenu menuWithItems:achievementsButton, nil];
    
    CCMenuItemImage *leaderboardsButton = [CCMenuItemImage itemFromNormalImage:@"GameCenterIcon.png" selectedImage:@"GameCenterIcon.png" target:self selector:@selector(showLeaderboards:)];
    CCMenu *leaderboardsMenu = [CCMenu menuWithItems:leaderboardsButton, nil];

    
    CCMenuItemImage *menuButton = [CCMenuItemImage itemFromNormalImage:@"pausebutton1.png" selectedImage:@"pausebutton1.png" target:self selector:@selector(loadMenu)];
    CCMenu *menuButtonMenu = [CCMenu menuWithItems:menuButton, nil];
    
    CCMenuItem *enableDPad, *disableDPad;
    CCMenuItemToggle *controlToggleItem;

    enableDPad = [CCMenuItemFont itemFromString:@"D-Pad" target:self selector:@selector(toggleControls:)];
    disableDPad = [CCMenuItemFont itemFromString:@"Tilt" target:self selector:@selector(toggleControls:)];
    
    if (dPadOn== TRUE){
        controlToggleItem = [CCMenuItemToggle itemWithTarget:self selector:@selector(toggleControls:)items: enableDPad, disableDPad, nil];
    }
    else if (dPadOn == FALSE){
        controlToggleItem = [CCMenuItemToggle itemWithTarget:self selector:@selector(toggleControls:)items:disableDPad, enableDPad, nil];
    }
    CCMenu *controlMenu = [CCMenu menuWithItems:controlToggleItem, nil];
    
    //Schedules smoke to appear every 5 seconds 
    [self schedule:@selector(smokeEffectTimer:)interval:5];
    
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        id scaleUp = [CCScaleTo actionWithDuration:6.0f scale:1.10];
        id scaleDown = [CCScaleTo actionWithDuration:6.0f scale:1.0f];
        [textImage runAction:[CCRepeatForever actionWithAction: [CCSequence actions:scaleUp,scaleDown,nil]]];
        textImage.position = ccp(500,625);
                
        achievementsButton.scale = 0.6;
        achieveMenu.position = ccp(50,720);
        leaderboardsButton.scale = 0.6;
        leaderboardsMenu.position = ccp(50,650);
        playGameMenu.position = ccp(500,150);
        menuButton.scale = 0.30f;
        menuButtonMenu.position = ccp(975,720);
        
        creditsMenu.position=ccp(900,50);
        guideMenu.position = ccp(100,50);
                
        controlMenu.position = ccp(500,50); 
        
    }
    else {  
        backgroundImage.scale = 0.5f;
        textImage.position = ccp(screenSize.width*0.5,screenSize.height*0.8f);
        textImage.scale = 0.4f;
        id scaleUp = [CCScaleTo actionWithDuration:6.0f scale:0.5f];
        id scaleDown = [CCScaleTo actionWithDuration:6.0f scale:0.4f];
        [textImage runAction:[CCRepeatForever actionWithAction: [CCSequence actions:scaleUp,scaleDown,nil]]];
        
        achievementsButton.scale = 0.4;
        achieveMenu.position = ccp(screenSize.width*0.06,screenSize.height*0.9f);
        
        leaderboardsMenu.scale = 0.4;
        leaderboardsMenu.position = ccp(screenSize.width*0.06,screenSize.height*0.7f);

        playGameButton.scale = 0.5f;
        playGameMenu.position = ccp(screenSize.width*0.5,screenSize.height*0.20f);
        
        menuButtonMenu.scale = 0.20f;
        menuButtonMenu.position = ccp(250,160);
        
        creditsMenu.scale = 0.5f;
        guideMenu.scale = 0.5f;
        creditsMenu.position=ccp(310,-50);
        guideMenu.position = ccp(-75,-50);
        
        controlMenu.position = ccp(screenSize.width*0.3,-35);
        controlMenu.scale = 0.6f;
        
        backgroundImage.scale = 0.5f;
        
    }
    
    [self addChild:backgroundImage z:-10 tag:100];     
    [self addChild:textImage z:-10 tag:100];
    
    [self addChild: achieveMenu];
//    [self addChild:leaderboardsMenu];
    [self addChild:playGameMenu];
    [self addChild:creditsMenu];
    [self addChild:guideMenu];
    
    [self addChild:menuButtonMenu];
    [self addChild:controlMenu];
    
}

-(void)loadCreditsScene:(id)sender{
    [AudioManager playMenuButtonClick];
    CCScene *loadCreditsScene = [Credits node];
    [[CCDirector sharedDirector] pushScene: loadCreditsScene]; //'pushes' stat scene ontop of game scene
}

-(void)loadGuideScene:(id)sender{
    [AudioManager playMenuButtonClick];
    CCScene *loadGuideScene = [GuideScene node];
    [[CCDirector sharedDirector] pushScene: loadGuideScene]; //'pushes' stat scene ontop of game scene

//    [AudioManager playMenuButtonClick];
//    [[SceneManager sharedSceneManager] runSceneWithID:kGuideScene];    

}

-(void)smokeEffectTimer:(CCTimer*)dt{
    CGSize screenSize = [[CCDirector sharedDirector] winSize]; 
    CCParticleSmoke *smokeEffect = [[CCParticleSmoke alloc] init];
    smokeEffect.texture = [[CCTextureCache sharedTextureCache] addImage:@"smoke.png"];
    [smokeEffect setStartSize:40];
    [smokeEffect setEmissionRate:4];
    [smokeEffect setLife:2];
    smokeEffect.duration = 1;
    [smokeEffect setGravity:ccp(0,20)];
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad){
        smokeEffect.position = ccp(550,200);
    }
    else{
        smokeEffect.position = ccp(screenSize.width*0.5,screenSize.height*0.22f);

    }
    [self addChild:smokeEffect];
    smokeEffect.autoRemoveOnFinish = YES;  
}

//Changes to scrolling level select scene
-(void)levelSelect:(id)sender{
    [AudioManager playMenuButtonClick];
    CCScene *loadLevelSelect = [LevelSelect node];
    [[CCDirector sharedDirector] pushScene: loadLevelSelect]; //'pushes' stat scene ontop of game scene
    
//    [AudioManager playMenuButtonClick];
//    [[SceneManager sharedSceneManager] runSceneWithID:kLevelSelectScene];    
}

//Uses view controller to show achievements
-(void)showAchievements:(id)sender{
    CCLOG(@"Show Achievements Menu");
    [AudioManager playMenuButtonClick];
	GKAchievementViewController *achievements = [[GKAchievementViewController alloc] init];
	if (achievements != NULL)
	{
		achievements.achievementDelegate = self;
        [[[CCDirector sharedDirector] openGLView] addSubview:tempVC.view];
        [tempVC presentModalViewController:achievements animated: YES];
	}
}

-(void)showLeaderboards:(id)sender{
    CCLOG(@"Show Leaderboards");
    [AudioManager playMenuButtonClick];
    GKLeaderboardViewController *leaderboardController = [[GKLeaderboardViewController alloc] init];
    if (leaderboardController!=NULL){
        
        leaderboardController.category = kLeaderboard1;
        leaderboardController.timeScope = GKLeaderboardTimeScopeAllTime;
        [[[CCDirector sharedDirector] openGLView] addSubview:tempVC.view];
        
//        leaderboardController.leaderboardDelegate = self;
//          AppDelegate *delegate = [UIApplication sharedApplication].delegate;
        [tempVC presentModalViewController:leaderboardController animated:YES];
    }
    
}

//Removes view controller
- (void)achievementViewControllerDidFinish:(GKAchievementViewController *)viewController{
    [AudioManager playMenuButtonClick];
    [tempVC dismissModalViewControllerAnimated:YES];
    [tempVC.view removeFromSuperview];
}

-(void)leaderboardsViewControllerDidFinish:(GKLeaderboardViewController *)viewController{
    CCLOG(@"TEST");
    [AudioManager playMenuButtonClick];
    
    [tempVC dismissModalViewControllerAnimated:YES];
    [tempVC.view removeFromSuperview];
}

-(void)loadMenu{
    [AudioManager playMenuButtonClick];
    [[CCDirector sharedDirector] pause];
    CCScene *loadStatScene = [StatMenuScene node];
    [[CCDirector sharedDirector] pushScene: loadStatScene]; //'pushes' stat scene ontop of game scene
 
}

-(void)muteAction: (id) sender{
    if (soundToggle == FALSE){
        CCLOG(@"Mute Audio");
        [[SimpleAudioEngine sharedEngine] setMute:1];
        soundToggle=TRUE;
    }

    else if (soundToggle == TRUE){
        CCLOG(@"Enable Audio");
        [[SimpleAudioEngine sharedEngine] setMute:0];
        soundToggle=FALSE;
    }
}

//Toggle DPad or Accelerometer controls
-(void)toggleControls:(id) sender{
    if (dPadOn == TRUE){
        CCLOG(@"Disable DPAD");
        dPadOn = FALSE;
    }
    else if (dPadOn == FALSE){
        CCLOG(@"Enable DPAD");
        dPadOn = TRUE;
    }
}

+(void) fadeToScene:(CCScene*)scene
{
    // get the director
    CCDirector* director = [CCDirector sharedDirector];
    
    // create transition scene
    CCScene* transition = [CCTransitionFade transitionWithDuration:2.0f scene:scene];
    
    // run this scene...
    if( director.runningScene == nil )
        [director runWithScene:transition];
    
    // ...or replace the current scene
    else
        [director replaceScene:transition];
}





-(void) feedback:(id) sender{
    NSURL *url = [NSURL URLWithString:@"http://www.surveymonkey.com/s/3D238XB"];
    
    if (![[UIApplication sharedApplication] openURL:url]){        
        CCLOG(@"%@%@",@"Failed to open url:",[url description]);
    }
    
}




- (void) dealloc
{
    [[SimpleAudioEngine sharedEngine] unloadEffect:@"level3Music.wav"];
    [super dealloc];
}
@end
